/**
 * Copyright (c) 2025 myons Inc. All rights reserved.
 */
package cn.zmwh.manage.api.modules.tools.service;

import cn.hutool.core.util.StrUtil;
import cn.zmwh.common.core.api.Result;
import cn.zmwh.common.core.constants.RedisKeyConstants;
import cn.zmwh.common.core.enums.CodeEnum;
import cn.zmwh.common.core.utils.RedisUtils;
import cn.zmwh.common.core.utils.SNUtils;
import cn.zmwh.common.security.base.UserService;
import cn.zmwh.manage.api.modules.tools.entity.request.SendCodeRequest;
import cn.zmwh.manage.api.modules.tools.entity.vo.SendCodeResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @describe: 、
 * @author: dmzmwh 、
 * @time: 2025-04-05 10:12 、
 */
@Slf4j
@Service
public class CodeSendService {

    @Autowired
    RedisUtils redisUtils;
    @Autowired
    UserService userService;

    public Result sendCode(SendCodeRequest req) {
        SendCodeResponse response = new SendCodeResponse();
        String origin = req.getOrigin();
        String type = req.getType();
        String mobile = req.getMobile();
        String email = req.getEmail();
        CodeEnum codeEnum = CodeEnum.getEnumByKey(type);
        if (codeEnum == null) {
            return Result.failed("验证码类型错误");
        }
        String version = "天天-Love";
//        TlOrigin tlOrigin = tlOriginService.getOne(Wrappers.<TlOrigin>lambdaQuery()
//                .eq(TlOrigin::getCode, origin));
//        if (tlOrigin != null) {
//            version = tlOrigin.getName();
//        }
        String smsCode = SNUtils.genSMSCode();
        String contentStr = codeEnum.getContent();
        Integer time = codeEnum.getTime();

        String content = StrUtil.format(contentStr, version, smsCode, time);
        String codeKey = RedisKeyConstants.SEND_CODE + codeEnum.getSign() + (StrUtil.isNotEmpty(mobile) ? mobile : email);
        redisUtils.set(codeKey, smsCode);
        redisUtils.expireTimeUnit(codeKey, time, TimeUnit.MINUTES);
        if (StrUtil.isNotEmpty(mobile)) {
            //发送手机验证码
//            SmsUtils.sendYZM(mobile, content, smsCode);
            return Result.ok(response);
        } else {
//            String result = MailUtil.send(email, version, content, true);
//            log.info(email + "发送验证码" + result);
            response.setTt(smsCode);
            return Result.ok(response);
        }
    }
}
